﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using t_205_verk_hopur_12.Models;
using System.Web.Security;
using t_205_verk_hopur_12.Helpers;

namespace t_205_verk_hopur_12.Models
{
    public class UserController : Controller
    {
        UserRepository userRepo = new UserRepository();
        Tool toolkit = new Tool();
        //
        // GET: /User/

        // Displays the info of a logged in user
        [Authorize]
        public ActionResult Index()
        {
            OwnerChannelsViewModel userInfo = new OwnerChannelsViewModel();

            userInfo.User = toolkit.GetCurrentUser();
            userInfo.ownedChannels = userRepo.GetOwnedChannels(toolkit.GetCurrentUser().ID);
            userInfo.subscribedChannels = userRepo.GetSubscribedChannels(toolkit.GetCurrentUser().ID);
            userInfo.employeeAtChannels = userRepo.GetEmployedAtChannels(toolkit.GetCurrentUser().ID);

            return View(userInfo);
        }

        // Displays user info
        public ActionResult Details(int id)
        {            
            User user = userRepo.GetUserByID(id);

            if (user == null)
            {
                return View("NotFound");
            }
            
            return View(user);
        }

        // To get a view to edit the user info
        [Authorize]
        public ActionResult Edit()
        {
            return View(toolkit.GetCurrentUser());
        }

        // To post the user info changes to our database
        [Authorize]
        [HttpPost]
        public ActionResult Edit(User editedUser)
        {
            User currentUser = toolkit.GetCurrentUser(userRepo);

            if(ModelState.IsValid)
            {
                // To store the current password
                string oldPassword = currentUser.Password;

                UpdateModel(currentUser);

                AccountMembershipService ams = new AccountMembershipService();

                // To update the password in the Membership system
                ams.ChangePassword(currentUser.Username, oldPassword, currentUser.Password);

                // To finally save the user changes to our database
                userRepo.Save();

                return RedirectToAction("Index");
            }

            return View(currentUser);
        }
    }
}
